package edu.hawaii.duedates.messenger;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/** 
 * This Email object sends DueDates reports.
 * 
 * @author Ronn Reeves and Robin Raqueno
 */
public class Email implements IEmail {
  
  /** Session object. */ 
  private final Session session;

  /** Sender of email. */ 
  private static final String sender = "DueDates-Silver Admin <noreply@duedates-silver.org>";
  
  /** Recipient of email. */
  private final String recipient;

  /** Subject of email. */
  private static final String subject = "[DueDates-Silver] Library Books Coming Due";
  
  /** Body of email. */
  private final String body;
  
  /** 
   * Instance of the email object.
   * 
   * @param recipient The recipient of the email.
   * @param smtpServer The email server (mail.domain.ext).
   * @param body The body of the email.
   */
  public Email(String recipient, String smtpServer, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    this.session = Session.getInstance(props);
    this.recipient = recipient;
    this.body = body;
  }  

  
  /** 
   * Attempts to send an email.  Returns true if this email successfully sent, otherwise false. 
   * 
   * @return True if successful; false otherwise.
   */ 
  public boolean send() {
    try { 
      Message msg = new MimeMessage(this.session); 
      InternetAddress senderAddress = new InternetAddress(sender); 
      InternetAddress[] senderAddressArray = {senderAddress};
      InternetAddress recipientAddress = new InternetAddress(recipient); 
      msg.setFrom(senderAddress); 
      msg.setReplyTo(senderAddressArray); 
      msg.setRecipient(Message.RecipientType.TO, recipientAddress); 
      msg.setSubject(subject); 
      msg.setSentDate(new Date());
      msg.setText(this.body);
      Transport.send(msg);

      return true;
    } 
    
    catch (MessagingException e) { 
      return false; 
    }
  }  
}